import os
import threading
import time
from datetime import datetime

from PIL import Image
from io import BytesIO

from base import flux_ali
from base import oss_client
from model.models import db, TSysNovelChapter, TSysFile

images_temp_path = "../images_temp"
type_PNG="png"
def create_images_from_prompt(playboosks_json, chapter_id):

    images_temp_path_by_novel_chapter = images_temp_path + os.sep + str(chapter_id) + "-" + str(time.time_ns())

    if playboosks_json is None:
        return {"success": False, "value": None, "msg": "playboosks_json为空"}
    if playboosks_json.get("value") is None:
        return {"success": False, "value": None, "msg": "playboosks_json为空"}

    #素材
    materials =[]
    image_no=1
    timestamp = get_current_timestamp()
    for playbook_json in playboosks_json.get("value"):
        no = 0
        subtitles_json = playbook_json.get("subtitles")
        for pic_promopt in playbook_json.get("pic_promopts"):
            material = {}
            result = flux_ali.sample_block_call_with_retry(pic_promopt.get("pic_promopt"), file_path=images_temp_path_by_novel_chapter, max_retry_count=3)
            if result.get("success") == True:
                if len(subtitles_json)-1 < no:
                    # return {"success": False, "value": None, "msg": "生成图片异常，字幕为空"}
                    print("图片提示词多于字幕数量,已忽略此条")
                    continue
                subtitle = subtitles_json[no]
                no = no + 1

                chapter = TSysNovelChapter.query.filter_by(id=chapter_id).first()
                if chapter is not None:
                    file_name=str(chapter_id)+"-"+ timestamp +"-"+str(image_no)+".png"
                    bucket_name = "imgs" + "-" + str(chapter.user_id) + "-" + str(chapter_id)
                    oss_client.upload_file(file_path=result.get("value"), file_name=file_name, bucket_name=bucket_name)
                    tSysFile = TSysFile(
                        user_id=chapter.user_id,
                        correlation_id=chapter.novel_id,
                        correlation_type='novel',
                        correlation_sub_id=chapter_id,
                        name=chapter.title,
                        local_path=file_name,
                        remote_path=bucket_name,
                        file_type=type_PNG,
                        create_date=datetime.now(),
                        update_date=datetime.now()
                    )
                    db.session.add(tSysFile)
                    db.session.commit()

                    material["no"] = image_no
                    material["image_path"] = result.get("value")
                    material["oss_file_name"] = file_name
                    material["subtitle"] = subtitle
                    materials.append(material)
                    print("第" + str(image_no) + "张图生成完毕！")
                image_no = image_no + 1
            else:
                print("第" + str(image_no) + "张图生成失败 ！")

    return {"success": True, "value": {"imgs_path":images_temp_path_by_novel_chapter,"materials":materials}, "msg": "图片及字幕素材创建完毕"}

#异步生成并下载图片
def create_images_from_prompt_ansy(playboosks_json, chapter_id):

    images_temp_path_by_novel_chapter = images_temp_path + os.sep + str(chapter_id) + "-" + str(time.time_ns())

    if playboosks_json is None:
        return {"success": False, "value": None, "msg": "playboosks_json为空"}
    if playboosks_json.get("value") is None:
        return {"success": False, "value": None, "msg": "playboosks_json为空"}

    #线程池
    # threadPool = ThreadPoolExecutor(max_workers=16, thread_name_prefix="create_img_")
    #素材
    thread_no = 0
    materials =[]

    try:
        # create_img_thread = threading.Thread(target=create_image_and_download,
        #                                      args=(materials, pic_promopt.get("pic_promopt"),
        #                                 images_temp_path_by_novel_chapter,subtitles_json[no]), name="create_image_and_download" + str(thread_no))
        tasks = []
        for playbook_json in playboosks_json.get("value"):
            no = 0
            subtitles_json = playbook_json.get("subtitles")
            for pic_promopt in playbook_json.get("pic_promopts"):
                create_img_thread = threading.Thread(target=create_image_and_download,
                                                     args=(pic_promopt.get("pic_promopt"),
                                                           images_temp_path_by_novel_chapter, subtitles_json[no]),
                                                     name="create_image_and_download" + str(thread_no))
                no = no + 1
                create_img_thread.start()

    except Exception as e:
        print(e)

    return {"success": True, "value": {"imgs_path":images_temp_path_by_novel_chapter,"materials":materials}, "msg": "图片及字幕素材创建完毕"}

def create_image_and_download(prompt, file_path, subtitle):
    material = {}
    try:
        result = flux_ali.sample_block_call(prompt, file_path=file_path)
        if result.get("success") == True:
            material["image_path"] = result.get("value")
            material["subtitle"] = subtitle
        print("finish")
    except Exception as e:
        print(e)
    return material
    # 上传图片到oss
    # 图片入库


def get_current_timestamp():
    t = time.time()
    time_string = time.strftime("%Y-%m-%d-%H-%M", time.localtime(t))
    return time_string

def resize_image(image_file, desired_size):
    # 打开一张图片文件
    with Image.open(image_file) as img:
        # 调整图片大小到目标尺寸
        img = img.resize(size=desired_size)
        # 将调整后的图片保存到临时文件
        img_byte = BytesIO()
        img.save(img_byte, format='PNG')  # format: PNG or JPEG
        return img_byte

